/*
 * 左侧 背景维度
 * @Author: mikey.zhaopeng
 * @Date:   2016-05-04 14:32:13
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:12:25
 */

'use strict';
define([
    '../../framework/base/baseView',
    '../../framework/bean/ec',
    '../../framework/bean/common',
    '../../framework/bean/feed'
], function(
    BaseView,
    ecModel,
    commonModel,
    feedModel
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;
        this.init = function(feedId) {
            self.$root = $('.query');
            self.$website = self.$root.find('select[name="select-website"]');
            self.$feed = self.$root.find('select[name="select-feed"]');
            self.$compareDimension = self.$root.find('select[name="compare-dimension"]');
            self.$timeRangeSince = self.$root.find('input[name=timeRange-since]');
            self.$timeRangeUntil = self.$root.find('input[name=timeRange-until]');
            self.$queryBtn = self.$root.find('.btn-query');
            self.$filterIcon =  self.$root.find('.filter-icon');

            ecModel.allWebSite(function(results) {
                self.websites = results;
                self._renderWebsite(results);
                self._renderFeed([], true);
                self._renderDimension([], true);
            });


            commonModel.timestamp(function(date) {
                self.nowDate = date.date;
                self.timezoneId = window.sessionStorage.timezoneId + ':00';
                self.timezoneValue = window.sessionStorage.timezoneValue;
                self.renderTimeRange();
            });

            self.event();
        }

        this.event = function(){
            self.$queryBtn.off('click').on('click', function(e){
                self.$root.trigger('queryBtnClick');
            });

            self.filterEvent();
        }

        this.filterEvent = function (){
            self.$filterIcon.off('click').on('click', function(e){
                if ($(this).hasClass("disabled")){
                    return;
                }
                $(this).addClass("disabled");
                $(".filter-condition-container").removeClass("hide");
                $(".search-result-area").addClass("hide");
                $(".query-btn-area").addClass("hide");
            })

            $(".filter-cancel-btn", ".filter-condition-container").off("click").on("click", function(e){
                self.$filterIcon.removeClass("disabled");
                $(".filter-condition-container").addClass("hide");
                $(".search-result-area").removeClass("hide");
                $(".query-btn-area").removeClass("hide");
            })

            $(".filter-ok-btn", ".filter-condition-container").off("click").on("click", function(e){
                self.$filterIcon.removeClass("disabled");
                $(".filter-condition-container").addClass("hide");
                $(".search-result-area").removeClass("hide");
                $(".query-btn-area").removeClass("hide");

                $(".query-result-area").empty();
                var _items = $(".filter-condition-container").find(".filter-item");
                $.each(_items, function(i, _item) {
                    if (!$(_item).parents(".filter-block").hasClass("hide")){
                        if ($(_item).hasClass("select2-c")) {
                            //select2
                            var datas = $(_item).find("select").select2("data");
                            if (datas.length){
                                var _resultHtml = $('<div class="query-result-item" key="' + $(_item).attr("key") +  '"><span class="tag-title">' +  self.kit.translate('abTest', $(_item).attr("key") + "Colon") +'</span> <ul class="tag-container"> </ul> </div>');
                                $(".query-result-area").append(_resultHtml);
                                var _tagUl = _resultHtml.find(".tag-container");
                                var tagItem;
                                $.each(datas, function(i, _data){
                                    tagItem = $('<li class="tag">'
                                        + '<span class="tag-remove">×</span>'
                                        +  _data.text
                                        + '</li>');
                                    tagItem.data("data", _data);
                                    _tagUl.append(tagItem)
                                })
                            }
                        } else {
                            //复选框
                            var datas = $(_item).find('input[type="checkbox"]:checked');
                            if (datas.length){
                                var _resultHtml = $('<div class="query-result-item" key="' + $(_item).attr("key") +  '"><span class="tag-title">' +  self.kit.translate('abTest', $(_item).attr("key")  + "Colon" ) +'</span> <ul class="tag-container"> </ul> </div>');
                                $(".query-result-area").append(_resultHtml);
                                var _tagUl = _resultHtml.find(".tag-container");
                                var tagItem;
                                $.each(datas, function(i, _data){
                                    tagItem = $('<li class="tag">'
                                        + '<span class="tag-remove">×</span>'
                                        +  $(_data).attr("name")
                                        + '</li>');
                                    tagItem.data("data", {"id": $(_data).attr("value"), "text": $(_data).attr("value")});
                                    _tagUl.append(tagItem)
                                })
                            }
                        }
                    }

                })

                self.$root.trigger("tagChanged");
                $(".fmp-article").scrollTop(0);
                $(".tag-remove", ".query-result-area").off("click").on("click", function(){
                    var _p = $(this).parent("li");
                    var _tagC = _p.parent(".tag-container");
                    var _item = _tagC.parent(".query-result-item");
                    var _tag = _p.data("data");
                    _p.remove();
                    var _filterItem = $('div.filter-item[key="'+ _item.attr("key") +  '"]');
                    if (_filterItem.hasClass("select2-c")){
                        var selected = _filterItem.find("select").val();
                        var dIndex = selected.indexOf(_tag.id);
                        selected.splice(dIndex,1);
                        _filterItem.find("select").val(selected);
                        _filterItem.find("select").trigger("change");
                    } else {
                        _filterItem.find('input[value="'+ _tag.id +'"]').prop("checked", false);
                    }

                    if (!_tagC.find("li").length){
                        _item.remove();
                    }
                    self.$root.trigger("tagChanged");
                })
            })
        }

        this.renderTimeRange = function() {
            var initStart = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(6, 'days');
            var initEnd = moment(self.nowDate).utcOffset(self.timezoneValue);
            var config = self.getDatarangeConfig();
            config.startDate = initStart;
            config.endDate = initEnd;
            self.$root.find('.timeRange-range').daterangepicker(config, self.setTimeRange);
            self.setTimeRange(initStart, initEnd);
        }

        this.getDatarangeConfig = function(setMinDate) {
            var today = moment(self.nowDate).utcOffset(self.timezoneValue),
                yesterday = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(1, 'days'),
                forward_3_day = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(2, 'days'),
                forward_7_day = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(6, 'days'),
                forward_30_day = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(29, 'days'),
                forward_90_day = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(89, 'days'),
                thisMonthBegin = moment(self.nowDate).utcOffset(self.timezoneValue).startOf('month'),
                thisMonthEnd = moment(self.nowDate).utcOffset(self.timezoneValue).endOf('month'),
                lastMonthBedin = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(1, 'month').startOf('month'),
                lastMonthEnd = moment(self.nowDate).utcOffset(self.timezoneValue).subtract(1, 'month').endOf('month');
            var daysOfWeek = [
                I18N.getText('common', 'date_weekends'),
                I18N.getText('common', 'date_monday'),
                I18N.getText('common', 'date_tuesday'),
                I18N.getText('common', 'date_wednesday'),
                I18N.getText('common', 'date_thursday'),
                I18N.getText('common', 'date_friday'),
                I18N.getText('common', 'date_saturday')
            ];
            var monthNames = [
                I18N.getText('common', 'date_january'),
                I18N.getText('common', 'date_february'),
                I18N.getText('common', 'date_march'),
                I18N.getText('common', 'date_april'),
                I18N.getText('common', 'date_may'),
                I18N.getText('common', 'date_june'),
                I18N.getText('common', 'date_july'),
                I18N.getText('common', 'date_august'),
                I18N.getText('common', 'date_september'),
                I18N.getText('common', 'date_october'),
                I18N.getText('common', 'date_november'),
                I18N.getText('common', 'date_december')
            ];

            var config = {
                timezone: self.timezoneValue,
                opens: 'left',
                format: 'YYYY-MM-DD',
                maxDate: new Date(self.nowDate),
                locale: {
                    applyLabel: I18N.getText('management', 'dateApplyLabel'),
                    cancelLabel: I18N.getText('management', 'dateCancelLabel'),
                    fromLabel: I18N.getText('management', 'dateFromLabel'),
                    toLabel: self.timezoneId,
                    customRangeLabel: I18N.getText('management', 'dateCustomRangeLabel'),
                    daysOfWeek: daysOfWeek,
                    monthNames: monthNames,
                    firstDay: 0
                },
                ranges: {}
            };
            config.ranges[I18N.getText('management', 'dateRanges1')] = [today, today];
            config.ranges[I18N.getText('management', 'dateRanges2')] = [yesterday, today];
            config.ranges[I18N.getText('management', 'dateRanges3')] = [forward_3_day, today];
            config.ranges[I18N.getText('management', 'dateRanges7')] = [forward_7_day, today];

            if (setMinDate) {
                config.minDate = forward_90_day;
            }
            return config;
        }

        this.setTimeRange = function(start, end) {
            var since = start.format("YYYY-MM-DD");
            var until = end.format("YYYY-MM-DD");
            self.$timeRangeSince.val(since);
            self.$timeRangeUntil.val(until);
            var tpl = '<div>' +
                '<span>' + start.format("YYYY-MM-DD") + I18N.getText('management', 'to') + end.format("YYYY-MM-DD") + '</span>' +
                '<i class="glyphicon glyphicon-calendar fa fa-calendar pull-right"></i>' +
                '</div>';
            self.$root.find('.timeRange-range').html(tpl);
        }

        this._renderDimension = function(results, _disabled){
            results.unshift({id : -1, text : I18N.getText('abTest', 'plseChooseDimension')});
            //维度
            self.$compareDimension.empty().select2({
                data : results,
                placeholder : '维度'
            }).off("select2:select").on('select2:select', function (evt) {
                self.renderFilterArea(self.filterDimension);
                $(".filter-cancel-btn", ".filter-condition-container").trigger("click");
                $(".query-result-area").empty();
                self.$root.trigger("tagChanged");
                // Do something
                var d = evt.params.data.id;
                if (d  == -1){
                    self.$filterIcon.addClass("disabled");
                } else {
                    $(".filter-condition-container").find('.' + d + '-block').addClass("hide");
                    self.$filterIcon.removeClass("disabled");
                }
                //
            });

            self.$compareDimension.prop("disabled", _disabled)
        }

        this._renderWebsite = function(results) {
            $.each(results, function(i, result){
                result.id = result.productManageProductId;
                result.text =  result.webSite;
            });
            results.unshift({id : -1, text : I18N.getText('abTest', 'plseChooseWebsite')});
            //self.$website.append(html);
            self.$website.empty().select2({
                placeholder : I18N.getText('abTest', 'plseChooseWebsite'),
                data : results
            }).off("select2:select").on('select2:select', function (evt) {
                // Do something
                self.renderFeed();
                $(".filter-cancel-btn", ".filter-condition-container").trigger("click");
                self.$filterIcon.addClass("disabled");
                $(".query-result-area").empty();
                self.$root.trigger("tagChanged");
            });
        }

        this.renderFeed = function(e) {
            self.prodId = self.$website.val();
            if (self.prodId == -1) {
                self._renderFeed([], true);
                //self.$root.trigger('websiteClear'); //清空数据
                return;
            }
            var params = {
                prodId: self.prodId
            }
            feedModel.findByProd(params, function(results) {
                self.feeds = results;
                self._renderFeed(results, false);
            });
        }

        this._renderFeed = function(results, _disabled) {

            $.each(results, function(i, result){
                result.id = result.id;
                result.text = result.feedName;
            })
            results.unshift({
                id : -1,
                text : I18N.getText('abTest', 'plseChooseFeed')
            })
            self.$feed.empty().select2({
                placeholder : I18N.getText('abTest', 'plseChooseFeed'),
                data : results
            }).off("select2:select").on("select2:select", function(e){
                self.renderDimension();
                $(".filter-cancel-btn", ".filter-condition-container").trigger("click");
                self.$filterIcon.addClass("disabled");
                $(".query-result-area").empty();
                self.$root.trigger("tagChanged");
            });
            self.$feed.prop("disabled", _disabled)
        }

        this.renderDimension = function(){
            var params = {
                feedId: self.$feed.val()
            }
            ecModel.fullCondition(params, function(result) {
                var datas = [];
                _.map(result, function(val, key, arr) {
                    var list = val.list||val.ecTemplateMateriel||val.audienceGroup||val.productSetList||[];
                    if (list.length > 0) {
                        console.log(key)
                        datas.push({
                            id : key,
                            text : self.kit.translate('abTest', key)
                        })
                    }
                });
                self.filterDimension = result;
                self._renderDimension(datas, false);
                self.renderFilterArea(result);
            });
        }

        this.renderFilterArea = function(_filters){
            _.map(_filters, function(val, key) {
                var list = val.list||val.ecTemplateMateriel||val.audienceGroup||val.productSetList||[];
                var _block = $("." + key + "-block", ".filter-condition-container");
                if (list.length > 0) {
                    _block.removeClass("hide");
                    if ("audienceManager" == key || "ecTemplateMateriel" == key || "productSet" == key){
                        $.each(list, function(i, _data){
                            _data.text = _data.name;
                        })

                        $('select[name="' + key +'"]', ".filter-condition-container").empty().select2({
                            multiple: true,
                            placeholder: $('select[name="' + key +'"]', ".filter-condition-container").attr("placeholder"),
                            data: list
                        })
                    } else {
                        var _html = '';

                            $.each(list, function(i, _data){
                            var _val;
                            var _text;
                            if (_data.name){
                                _val = _data.name;
                                _text = self.kit.translate('abTest', _data.name);
                            } else {
                                _val = _data;
                                _text = self.kit.translate('abTest', _data);

                            }

                             _html += '<input type="checkbox"  id="' + (key + i) + '" value="' + _val +  '" name="' + _text + '"class="form-input" >'
                                    + '<label for="' + (key + i) +'" class="filter-check-label" >'
                                    + '<span class="checkbox-mark"></span>'
                                    + _text
                                    + '</label>';
                        })

                        $(".filter-item", _block).html(_html);
                    }
                } else {
                    _block.addClass("hide");
                }
            })
        }

        this.valicateParams = function() {
            //站点
            if (self.$website.val() == -1){
                self.kit.alert2(I18N.getText('abTest', 'plseChooseWebsite'));
                self.$website.focus();
                return true;
            }

            //feed
            var feed = self.$feed.val();
            if (!feed || feed == -1 || feed == ""){
                self.kit.alert2(I18N.getText('abTest', 'plseChooseFeed'));
                self.$feed.focus();
                return true;
            }

            //维度
            var group = self.$compareDimension.val();
            if (!group ||  group == -1 || group == ""){
                self.kit.alert2(I18N.getText('abTest', 'plseChooseContrastDimension'));
                self.$compareDimension.focus();
                return true;
            }

            return false;
        }

        this.getParams = function() {

            if (self.valicateParams()) {
                return true;
            }

            var site = _.findWhere(self.websites, { productManageProductId: self.$website.val() });
            if ((site == undefined) || (site.fbAccounts == undefined) || (site.fbAccounts.length == 0)) {
                self.kit.alert2(I18N.getText('abTest', 'noAccount'))
                return true;
            }

            //背景过滤
            var filterParam = self.getFilterParam();
            var params = {
                accountId: site.fbAccounts,
                feedId: self.$feed.val(),
                group: self.$compareDimension.val(),
                day: {
                    since: self.$timeRangeSince.val(),
                    until: self.$timeRangeUntil.val()
                }
            }
            var groupCol = {
                'ecTemplateMateriel': 'creativeTemplate',
                'billingEvent': 'billingEvent',
                'optimizationGoal': 'optimizationGoal',
                'placement': 'placement',
                'bid': 'bid',
                'audienceManager': 'audienceTemplate',
                'productSet': 'productSet'
            };
            params.group = groupCol[params.group] || 'placement';

            params = $.extend(params, filterParam);
            return params
        }

        this.getFilterParam = function(){
            var param = {};
            var filterBlocks = $(".query-result-area").find(".query-result-item");
            if (filterBlocks.length){
                $.each(filterBlocks, function(i, _filterBlock){
                    var tags = $(_filterBlock).find(".tag", ".tag-container");
                    if (tags.length){
                        var valus = []
                        $.each(tags, function(i, _tag){
                            valus.push($(_tag).data("data").text);
                        })
                        param[$(_filterBlock).attr("key")] = valus;
                    }
                })
            }
            return param;
        }

        this.destroy = function() {
            self.$root.empty();
        }
    }
    return me;
});
